package com.hantang.web.dao;


import java.io.Serializable;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;


public class BaseDao {
	 private static final Logger logger = Logger.getLogger(BaseDao.class);
	 protected Session session = null;	  
	 
	 protected void openSession()
	 {
		 this.closeSession();
		 SessionFactory sessonFactory = ElbSessionFactory.getInstance().getSessionFactory();
		 this.session = sessonFactory.openSession();
	 }
	 protected void closeSession()
	 {		
		 if(this.session != null)
		 {
			 this.session.close();			 
			 this.session = null;
		 }
	 }
	 
	 protected void save(Object obj)
	 {
		 if(obj!= null)
		 {
			 Transaction tx =null;
			 try{
				 this.openSession(); 
				 tx = this.session.beginTransaction();
				 this.session.save(obj);
				 tx.commit();				 
			 }catch(HibernateException e){
				 logger.error(e.getStackTrace());
				 e.printStackTrace();
				 if(tx != null){
					tx.rollback();
				 }
			 }
			 finally{
				 this.closeSession();				 
			 }
		 }
	 }
	 
	 protected void saveOrUpdate(Object obj)
	 {
		 if(obj!= null)
		 { 
			 Transaction tx = null;
			 try{
				 this.openSession(); 
				 tx = this.session.beginTransaction();
				 this.session.saveOrUpdate(obj);
				 tx.commit();
			 }catch(HibernateException e){
				 logger.error(e.getStackTrace());
				 e.printStackTrace();
				 if(tx!= null){
					 tx.rollback();
				 }
			 }
			 finally{
				 this.closeSession();				 
			 }
		 }
	 }
	 protected void update(Object obj)
	 {
		 if(obj != null)
		 {
			 Transaction tx = null;
			 try{
				 this.openSession();	
				 tx = this.session.beginTransaction();
				 this.session.update(obj);
				 tx.commit();
			 }catch(HibernateException e){
				 logger.error(e.getStackTrace());
				 e.printStackTrace();
				 if(tx != null){
					 tx.rollback();
				 }
			 }
			 finally{
				 this.closeSession();				 
			 }
		 }
	 }
	 protected boolean delete(Object obj)
	 {
		 boolean isOk = false;
		 if(obj!=null)
		 {
			 Transaction tx = null;
			 try{
				 this.openSession();
			 	tx = this.session.beginTransaction();
			 	this.session.delete(obj);
			 	tx.commit();
			 	isOk = true;
			 }catch(HibernateException e){
				 logger.error(e.getStackTrace());
				 e.printStackTrace();
				 if(tx != null){
					 tx.rollback();
				 }
			 }
			 finally{
				 this.closeSession();				 
			 }
		 }
		 return isOk;
	 }
	 
	 @SuppressWarnings("unchecked")
	protected Object get(Class arg0, Serializable arg1)
	 {
		 Object obj=null;
		 Transaction tx = null;
		 try{
			 
			 this.openSession();
			 tx = this.session.beginTransaction();
			 obj = this.session.get(arg0, arg1);	
			 tx.commit();
		 }catch(HibernateException e){
			 logger.error(e.getStackTrace());
			 e.printStackTrace();
			 if(tx != null){
				 tx.rollback();
			 }
		 }
		 finally{
			 this.closeSession();				 
		 }
		 return obj;
	 }
	 
}
